import { createRouter, createWebHistory } from 'vue-router'
import Login from '../views/Login.vue'
import MainLayout from '../views/MainLayout.vue'
import ApiManagement from '../views/ApiManagement.vue'
import { ROUTES_CONFIG } from '../config/index.js'
import { useAuthStore } from '../stores/auth'

const routes = [
  {
    path: '/',
    redirect: ROUTES_CONFIG.main
  },
  {
    path: ROUTES_CONFIG.main,
    name: 'MainLayout',
    component: MainLayout,
    meta: { requiresAuth: true }
  },
  {
    path: ROUTES_CONFIG.login,
    name: 'Login',
    component: Login
  },
  {
    path: ROUTES_CONFIG.home,
    redirect: ROUTES_CONFIG.main
  },
  {
    path: ROUTES_CONFIG.apiManagement,
    name: 'ApiManagement',
    component: ApiManagement,
    meta: { requiresAuth: true }
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const authStore = useAuthStore()
  
  // 初始化认证状态
  authStore.initAuth()
  
  console.log('🚷️ 路由守卫检查:', {
    to: to.path,
    from: from.path,
    requiresAuth: to.meta.requiresAuth,
    isAuthenticated: authStore.checkAuth()
  })
  
  // 检查是否需要认证
  if (to.meta.requiresAuth && !authStore.checkAuth()) {
    console.log('❌ 需要认证但未登录，重定向到登录页面')
    // 重定向到登录页面
    next({ name: 'Login' })
  } else if (to.name === 'Login' && authStore.checkAuth()) {
    console.log('✅ 已登录用户访问登录页面，重定向到主页')
    // 已登录用户访问登录页面，重定向到主页
    next({ name: 'MainLayout' })
  } else {
    console.log('✅ 路由守卫通过，允许导航')
    next()
  }
})

export default router